import { Action, EventDefinition } from '@/types/event';
import { getChildren } from '@/utils';

export interface Layer {
  type: string; // 图层类型
  id: string; // 图层编号
  title: string; // 图层名称
  parent: string; // 父级图层
  enable: boolean; // 是否启用
  data: Record<string, any>; // 图层数据
  events: EventDefinition[];
}

export default function useStageLayer() {
  const layers = ref<Layer[]>([]); // 图层列表
  const layerId = ref<string>(''); // 当前选中图层
  const layerLoadedIdList = ref<string[]>([]); // 当前加载完成的 layerId
  const layerData = ref<any>({}); // 当前选中图层的数据
  const layerEventId = ref<string>(''); // 当前选中事件
  const layerEventData = ref<any>({}); // 当前选中事件的数据
  const layerEventActionId = ref<string>(''); // 当前选中动作
  const layerEventActionData = ref<any>({}); // 当前选中动作的数据

  // 初始化
  const init = (newLayers: Layer[]) => {
    layers.value = newLayers || [];
  };

  // 添加图层
  const addLayer = (layer: Layer) => {
    layerId.value = layer.id;
    layers.value.push({ ...layer });
  };

  // 删除图层
  const removeLayer = (newLayerId: string) => {
    const layerIdChildren = getChildren(layers.value, newLayerId);
    const layerIdList = layerIdChildren.concat(newLayerId);
    layers.value = layers.value.filter((layer) => !layerIdList.includes(layer.id));
    layerId.value = '';
  };

  // 更新图层
  const updateLayer = (newLayer: Layer) => {
    layers.value.forEach((layer) => {
      if (layer.id === newLayer.id) {
        Object.assign(layer, newLayer);
      }
    });
  };

  // layers、layerId 更新时，更新 layerData
  watch([layers, layerId], () => {
    const currentLayer = layers.value?.find((layer) => layer.id === layerId.value);
    layerData.value = currentLayer || {};
  });

  // 更新当前事件数据
  watch(layerEventId, () => {
    const currentEvent = layerData.value.events?.find(
      (event: EventDefinition) => event.id === layerEventId.value
    );
    layerEventData.value = currentEvent || {};
    layerEventActionId.value = currentEvent?.actions?.length ? currentEvent?.actions[0].id : '';
  });

  // 更新当前动作数据
  watch(layerEventActionId, () => {
    const currentAction = layerEventData.value.actions?.find(
      (action: Action) => action.id === layerEventActionId.value
    );
    layerEventActionData.value = currentAction || {};
  });

  return {
    layers,
    layerId,
    layerLoadedIdList,
    layerData,
    layerEventId,
    layerEventData,
    layerEventActionId,
    layerEventActionData,
    init,
    addLayer,
    removeLayer,
    updateLayer,
  };
}
